package com.qding.park.manager.web.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qding.park.common.core.annotation.log.OperationLogType;
import com.qding.park.common.core.annotation.log.SystemControllerLog;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.system.SystemUnKnown;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.export.DataField;
import com.qding.park.common.utils.export.ExportDataSource;
import com.qding.park.common.utils.export.excel.ExcelDataExportor;
import com.qding.park.common.utils.export.excel.MODE;
import com.qding.park.common.web.controller.BaseController;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.common.rest.domain.AnswerMsg;
import com.qding.park.manager.common.rest.domain.AnswerMsgFactoryImpl;
import com.qding.park.manager.common.rest.enums.ResponseCodeEnum;
import com.qding.park.manager.facade.statis.service.CarlockStatisFacade;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.TbCarlock;
import com.qding.park.manager.pojo.example.TbCarlockExample;
import com.qding.park.manager.pojo.example.TbCarlockExample.Criteria;
import com.qding.park.manager.service.statis.biz.CarLockStatisBiz;
import com.qding.park.manager.service.statis.mapper.TbCarlockStatisMapper;
import com.qding.park.manager.web.form.CarlockListForm;
import com.qding.park.manager.web.power.Power;

/**
 * @author Administrator 锁车单统计
 */
@RestController
@RequestMapping("/carlock")
public class Web_CarLockController extends BaseController {

	private static final Log _log = LogFactory.getLog(Web_CarLockController.class);

	@Autowired
	private CarlockStatisFacade carlockStatisFacade;

	@Autowired
	private TbCarlockStatisMapper tbCarlockMapper;

	@Autowired
	private CarLockStatisBiz carLockStatisBiz;

	/**
	 * 分页查询锁车单
	 * @param parkId
	 *            车场id
	 * @param carNum
	 *            车牌
	 * @param jumpPage
	 *            当前页码
	 * @param pageLength
	 *            页长度
	 * @return 统计查询
	 */
	@Power(visitPark = "#form.getParkId()")
	@RequestMapping("/list")
	@SystemControllerLog(description = "锁车单列表查询", operation = OperationLogType.carlock_list)
	public AnswerMsg list(@Valid CarlockListForm form, BindingResult result) {

		/* 解析验证结果 */
		super.analysisValid(result);
		/* 解析验证结果 */

		PowerInfo power = this.getPowerInfo();

		int jumpPageInt = Integer.valueOf(form.getJumpPage());
		int pageLengthInt = Integer.valueOf(form.getPageLength());

		// 初始化统计条件
		TbCarlockExample example = new TbCarlockExample();
		Criteria criteria = example.createCriteria();

		if (!StringUtils.isBlank(form.getParkId())) {
			// 车场号
			criteria.andParkIdEqualTo(form.getParkId());
		}
		if (!StringUtils.isBlank(form.getCarNum())) {
			// 车牌号
			// criteria.andCarnumEqualTo(carNum);
			criteria.andCarnumLike(form.getCarNum());
		}

		if (!power.isAdminIs()) {
			criteria.andParkIdIn(power.getParkList());
		}

		ParkDataResult dataResult = carlockStatisFacade.carLocklist(example, jumpPageInt, pageLengthInt);
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
		return answerMsg;
	}

	/**
	 * 锁车单导出
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @return
	 */
	@Power(visitPark = "#parkId")
	@SystemControllerLog(description = "锁车单报表导出", operation = OperationLogType.carlock_exportExcel)
	@RequestMapping("/exportExcel")
	@ResponseBody
	public AnswerMsg exportExcel(String startTime, String endTime, String parkId) {

		try {
			PowerInfo power = this.getPowerInfo();
			// 初始化统计条件
			final TbCarlockExample example = new TbCarlockExample();
			Criteria criteria = example.createCriteria();

			if (!power.isAdminIs()) {
				criteria.andParkIdIn(power.getParkList());
			}
			if (!StringUtils.isBlank(startTime)) {
				// 缴费开始时间
				criteria.andCreateTimeGreaterThanOrEqualTo(
						DateUtils.parseDate(startTime, DateUtils.DATE_FORMAT_DATETIME));
			}
			if (!StringUtils.isBlank(endTime)) {
				// 缴费开始时间
				criteria.andCreateTimeLessThanOrEqualTo(DateUtils.parseDate(endTime, DateUtils.DATE_FORMAT_DATETIME));
			}
			if (!StringUtils.isBlank(parkId)) {
				criteria.andParkIdEqualTo(parkId);
			}
			// 排序
			example.orderByCreateTimeDesc();

			final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
			String filename = "锁车单报表_" + sdf2.format(new Date());
			response.setHeader("Content-disposition",
					"attachment; filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
			OutputStream os = response.getOutputStream();
			DataField[] dataFields = new DataField[8];
			dataFields[0] = new DataField("订单号", "orderNum", 20);
			dataFields[1] = new DataField("订单状态", "orderStatus", 25);
			dataFields[2] = new DataField("用户账号", "tel", 20);
			dataFields[3] = new DataField("车牌", "carNum", 10);
			dataFields[4] = new DataField("锁定车场", "lockParkName", 30);
			dataFields[5] = new DataField("锁定开始时间", "startTime", 20);
			dataFields[6] = new DataField("锁定结束时间", "endTime", 20);
			dataFields[7] = new DataField("当前状态", "currentStatus", 40);

			new ExcelDataExportor<Object>(dataFields, new ExportDataSource<Object>() {
				@Override
				public List getData() {
					// 查询统计条件
					List<TbCarlock> carLockList = tbCarlockMapper.listByExample(example);
					List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
					int temp = 0;
					for (int i = 0; i < carLockList.size(); i++) {
						Map<String, Object> mapParam = new HashMap<String, Object>();
						TbCarlock tbCarlock = carLockList.get(i);
						temp = i;
						mapParam.put("orderNum", tbCarlock.getId());
						mapParam.put("orderStatus", carLockStatisBiz.getOrderStatusStr(tbCarlock));
						mapParam.put("tel", tbCarlock.getTel());
						mapParam.put("carNum", tbCarlock.getCarNum());
						mapParam.put("lockParkName", tbCarlock.getParkName());
						// 预定开始时间
						mapParam.put("startTime", tbCarlock.getStartTime() == null ? ""
								: DateUtils.formatDate(tbCarlock.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
						// 预定结束时间
						mapParam.put("endTime", tbCarlock.getEndTime() == null ? ""
								: DateUtils.formatDate(tbCarlock.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));
						mapParam.put("currentStatus", carLockStatisBiz.getCurrentStatus(tbCarlock));
						lists.add(mapParam);
					}
					return lists;
				}
			}, os, MODE.EXCEL).export();

			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(null);
			return answerMsg;
		} catch (Exception e) {
			SystemUnKnown ex = new SystemUnKnown(e, ExceptionMessage.createExceptionMessage(SystemUnKnown.default_Name,
					"未知Exception", "payStartTime=" + startTime + ",payEndTime=" + endTime));
			exceptionHandle.handle(ex);
			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createErrorAnserMsg(ResponseCodeEnum.SYSTEM_ERROR);
			return answerMsg;
		}
	}
}
